package com.webchat.chat.core.converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Owner on 2018/6/27.
 */
public class StringToDateConverter implements Converter<String, Date> {

    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";

    @Nullable
    @Override
    public Date convert(String value) {
        if(StringUtils.isEmpty(value)) { return null; }

        value = value.trim();

        try {

            if(value.contains("-")) {
                SimpleDateFormat formatter;
                if(value.contains(":")) {
                    formatter = new SimpleDateFormat(dateFormat);
                }else {
                    formatter = new SimpleDateFormat(shortDateFormat);
                }

                Date dtDate = formatter.parse(value);
                return dtDate;
            }else if(value.matches("^\\d+$")) {
                Long lDate = new Long(value);
                return new Date(lDate);
            }else if(value.matches("([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$")){
                Calendar calendar = Calendar.getInstance();
                String date = calendar.get(Calendar.YEAR) +"-" +(calendar.get(Calendar.MONTH) + 1)+"-" +calendar.get(Calendar.DAY_OF_MONTH)+ " "+value;
                SimpleDateFormat  formatter = new SimpleDateFormat(dateFormat);
                Date dtDate = formatter.parse(date);
                return dtDate;
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }

        throw new RuntimeException(String.format("parser %s to Date fail", value));
    }
}
